<template>
  <div class="app-container">
    <!-- 过滤器 -->
    <div class="filter-container">
      <span>姓名: </span>
      <el-input
        v-model="listQuery.name"
        placeholder="请输入姓名"
        style="width: 200px;"
        class="filter-item"
        clearable
        @clear="handleSearch"
      />
      <div style="width: 20px; display: inline-block;" />
      <span>住院号: </span>
      <el-input
        v-model="listQuery.admission_no"
        placeholder="请输入住院号"
        style="width: 200px;"
        class="filter-item"
        clearable
        @clear="handleSearch"
      />
      <div style="width: 20px; display: inline-block;" />
      <el-date-picker
        v-model="listQuery.days"
        type="date"
        format="yyyy-MM-dd"
        value-format="yyyy-MM-dd"
        placeholder="选择日期"
        style="width: 200px;"
        @change="handleSearch"
      />
      <div style="width: 20px; display: inline-block;" />
      <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table v-loading="listLoading" :data="pagedUserinfo" border fit highlight-current-row style="width: 100%">
      <el-table-column align="center" label="姓名" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="住院号" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.admission_no }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="手机号" width="80">
        <template slot-scope="scope">
          <span>{{ scope.row.phone }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="总训练时间" width="100">
        <template slot-scope="scope">
          <span
            :style="{
              color: scope.row.train_time_sum >= 1200 ? 'green' : 'red'
            }"
          >
            {{ formatTrainingTime(scope.row.train_time_sum) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="年-月-日" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.days }}</span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />
  </div>
</template>

<script>
import { ratingsTimeSum } from '@/api/nurse/ratings_time_sum' // 导入查询接口
import Pagination from '@/components/Pagination'

export default {
  name: 'RatingsTimeSum',
  components: { Pagination },
  data() {
    return {
      userinfo: [], // 原始数据
      filteredUserinfo: [], // 根据搜索条件筛选后的数据
      pagedUserinfo: [], // 当前页数据
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        days: this.getTodayDate(), // 设置默认日期为今天
        name: '', // 添加姓名搜索
        admission_no: '' // 添加住院号搜索
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 获取数据并进行筛选和分页
    getList() {
      this.listLoading = true

      ratingsTimeSum().then(response => {
        const filteredData = response.data.userinfo.map(item => ({
          name: item[0],
          admission_no: item[1],
          phone: item[2],
          train_time_sum: item[3], // 秒为单位的训练时间
          days: this.formatDate(item[4]) // 将 days 转换为标准日期格式
        }))

        this.userinfo = filteredData // 保存所有数据
        this.filterData() // 调用过滤数据的方法
        this.updatePagedUserinfo() // 更新当前页数据
        this.total = this.filteredUserinfo.length
        this.listLoading = false
      }).catch(error => {
        console.error('Failed to fetch data:', error)
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 根据姓名、住院号和日期筛选数据
    filterData() {
      const { days, name, admission_no } = this.listQuery
      this.filteredUserinfo = this.userinfo.filter(item => {
        const admissionNoMatch = admission_no === '' || item.admission_no.includes(admission_no)
        const nameMatch = name === '' || item.name.includes(name)
        const daysMatch = days ? item.days === days : true // 只有在 days 有值时才进行比较
        return admissionNoMatch && nameMatch && daysMatch
      })
    },
    // 更新当前页的数据
    updatePagedUserinfo() {
      const start = (this.listQuery.page - 1) * this.listQuery.limit
      const end = start + this.listQuery.limit
      this.pagedUserinfo = this.filteredUserinfo.slice(start, end)
    },
    // 处理搜索操作
    handleSearch() {
      this.filterData() // 重新筛选数据
      this.total = this.filteredUserinfo.length // 更新总数
      this.updatePagedUserinfo() // 更新当前页数据
    },
    // 格式化训练时间为分秒
    formatTrainingTime(seconds) {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}分${remainingSeconds}秒`
    },
    // 格式化日期
    formatDate(date) {
      const d = new Date(date)
      return `${d.getFullYear()}-${(d.getMonth() + 1).toString().padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`
    },
    // 获取今天的日期
    getTodayDate() {
      const today = new Date()
      return `${today.getFullYear()}-${(today.getMonth() + 1).toString().padStart(2, '0')}-${today.getDate().toString().padStart(2, '0')}`
    }
  }
}
</script>

<style scoped>
/* 搜索框样式 */
.search-bar {
  margin-bottom: 20px;
}
</style>
